package com.le.dub.service.task;

import com.le.dub.conf.RedisKey;
import com.le.dub.mobile.DubRecord;
import com.le.dub.service.IAppVoiceService;
import com.le.dub.service.IDubRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
@Slf4j
@Service
public class ExecuteVoiceTask {
    @Resource
    private IDubRecordService dubRecordService;
    @Resource
    private RedisTemplate template;
    @Resource
    private IAppVoiceService appVoiceService;
    @Async
     public void executeVoiceTask(Long dubRecordId) {
        //获取配音生成记录
        DubRecord dubRecord = dubRecordService.getById(dubRecordId);
        String key = RedisKey.submitVoice + dubRecord.getUserId();
        template.opsForValue().increment(RedisKey.executeVoiceNum);
        try {
            String path=appVoiceService.executeVoice(dubRecord);
            dubRecord.setGenerateStatus(2);
            dubRecord.setSoundUrl(path);
            log.info("Thread" + Thread.currentThread().getName());

         } catch (Exception e) {
            //报错就设置状态为错误
            log.error("executeVoice-error"+e.getMessage());
            dubRecord.setGenerateStatus(3);
            e.printStackTrace();
        } finally {
            //删除用户任务锁
            template.delete(key);
            //减少正在执行任务数量
            template.opsForValue().decrement(RedisKey.executeVoiceNum);
            dubRecordService.updateById(dubRecord);

        }

    }
}
